/**
 * Proyecto: Cognitum
 * Global IT Services 2008
 * @author Esanantonio
 * @author Mislas
 */
Ext.form.VTypes['numericMask'] = function(v){
    return /^[0-9]+(.[0-9]+)?$/.test(v);
};

Cognitum.Polizas.General.Componentes.Generales = Ext.extend(Karma.FB2, {

    esFlotilla: false,
    
    initComponent: function(){
    
        Ext.apply(this, {
            title: 'Poliza',
            column1items: [{
                fieldLabel: 'OT',
                name: 'Id',
                disabled: true
            }, {
                fieldLabel: 'No. Poliza',
                allowBlank: true,
                name: 'Folio',
                disabled: true
            }, {
                fieldLabel: 'Contratante',
                name: 'Contratante',
                entityName: 'Clientes',
                xtype: 'entity.link'
            }, {
                fieldLabel: 'Titular',
                allowBlank: true,
                name: 'Titular',
                entityName: 'ContactoSimple',
                xtype: 'entity.link',
                contextTriggers: [{
                    id: 'Contratante',
                    query: 'c.Cliente.Id =?'
                }]
            }, {
                fieldLabel: 'Co Titular',
                allowBlank: true,
                name: 'CoTitular',
                entityName: 'ContactoSimple',
                xtype: 'entity.link',
                contextTriggers: [{
                    id: 'Contratante',
                    query: 'c.Cliente.Id =?'
                }]
            }
            ,{
                fieldLabel: 'F. de Pago',
                name: 'FormaPago',
                xtype: 'enum.combo',
                enumName: 'Cognitum.Dominio.Polizas.FormaPagoEnum'
            }, {
                fieldLabel: 'Aseguradora',
                name: 'Aseguradora',
                entityName: 'Aseguradoras',
                xtype: 'entity.link'
            }, {
                fieldLabel: 'Inicio de Vigencia',
                xtype: 'datefield',
                name: 'VigenciaInicio'
            }, {
                fieldLabel: 'Fin de Vigencia',
                xtype: 'datefield',
                name: 'VigenciaFin'
            }, {
                fieldLabel: 'Estatus',
                name: 'EstatusPoliza',
                xtype: 'enum.combo',
                enumName: 'Cognitum.Dominio.Polizas.EstatusPolizaEnum',
                readonly: true,
                disabled: true
            }, {
                name: 'Ramo',
                fieldLabel: 'Ramo',
                entityName: 'Ramos',
                xtype: 'entity.link',
                preContext: [{
                    value: this.division,
                    query: 'r.DivisionOperativa = ' + this.division
                }]
            }, {
                name: 'SubRamo',
                fieldLabel: 'Sub Ramo',
                entityName: 'SubRamos',
                xtype: 'entity.link',
                contextTriggers: [{
                    id: 'Ramo',
                    query: 'r.Ramo.Id=?'
                }],
                subquery: this.esFlotilla ? 'r.Flotilla=1' : 'r.Flotilla=0'
            }, {
                fieldLabel: 'Agente',
                name: 'Agente',
                entityName: 'Agentes',
                xtype: 'entity.link',
                contextTriggers: [{
                    id: 'Aseguradora',
                    query: 'a.Aseguradora.Id=?'
                }]
            }, {
                fieldLabel: 'Direccion Fiscal',
                name: 'DireccionFiscal',
                entityName: 'Direcciones',
                xtype: 'entity.link',
                contextTriggers: [{
                    id: 'Contratante',
                    query: 'p.Cliente.Id=?'
                }]
            }, {
                fieldLabel: 'Direccion Envio',
                name: 'DireccionEnvio',
                entityName: 'Direcciones',
                xtype: 'entity.link',
                contextTriggers: [{
                    id: 'Contratante',
                    query: 'p.Cliente.Id=?'
                }]
            }, {
                fieldLabel: 'Direccion Cobro',
                name: 'DireccionCobro',
                entityName: 'Direcciones',
                xtype: 'entity.link',
                contextTriggers: [{
                    id: 'Contratante',
                    query: 'p.Cliente.Id=?'
                }]
            }, {
                fieldLabel: 'Renovable',
                name: 'Renovable',
                xtype: 'checkbox',
                checked: false
            }, {
                fieldLabel: 'Poliza original',
                name: 'PolizaOriginal',
                entityName: 'Polizas',
                xtype: 'entity.link',
                disabled: true
            }, {
                fieldLabel: 'Poliza nueva',
                name: 'PolizaNueva',
                entityName: 'Polizas',
                xtype: 'entity.link',
                disabled: true
            }
                ],
            column2items: [{
                fieldLabel: 'Moneda',
                name: 'Moneda',
                entityName: 'Monedas',
                xtype: 'entity.link'
            },{
                fieldLabel: 'Prima',
                name: 'Prima',
                disabled: this.esFlotilla && this.division != 1 && this.division != 2 && this.division != 3,
				xtype: 'moneyfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true,
                subtotal: true
            }, {
                fieldLabel: 'Gastos',
                name: 'Gastos',
				xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true,
                subtotal: true               
            }, {
                fieldLabel: 'Recargos %',
                name: 'RecargosPct',
				xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true
            }, {
                fieldLabel: 'Recargos',
                name: 'RecargosImporte',
				xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true,
                vtype: 'numericMask'
            }, {
                fieldLabel: 'Neto',
                name: 'Neto',
                xtype: 'numberfield',
				vtype: 'numericMask',
                readOnly: true,
                neto: true
            }, {
                fieldLabel: 'Descuento',
                name: 'Descuento',
                xtype: 'numberfield',                
                vtype: 'numericMask',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true
            }, {
                fieldLabel: 'Impuesto %',
                name: 'Impuesto',
                entityName: 'Impuestos',
                xtype: 'entity.link',
                listeners: {
                    'set': {
                        fn: this.calculaMonto,
                        scope: this
                    }
                },
                additionalProperties: ['Porcentaje']
            }, {
                fieldLabel: 'Impuesto',
                name: 'ImpuestoImporte',
				xtype: 'numberfield',
                enableKeyEvents: true,
                readOnly: true
            }, {
                fieldLabel: 'Total',
                name: 'Total',
				xtype: 'numberfield',
                readOnly: true
            }, {
                fieldLabel: 'Estatus Cobranza',
                name: 'EstatusCobranza',
                xtype: 'enum.combo',
                enumName: 'Cognitum.Dominio.Polizas.EstatusCobranzaEnum',
                disabled: true
            }, {
                fieldLabel: 'Comision %',
                name: 'ComisionPct',
				xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true
            }, {
                fieldLabel: 'Comision',
                name: 'ComisionImporte',
                xtype: 'moneyfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true,
                vtype: 'numericMask'
                
            }, {
                fieldLabel: 'SobreComision %',
                name: 'SobreComisionPct',
                xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true
            }, {
                fieldLabel: 'SobreComision',
                name: 'SobreComisionImporte',
                xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true,
                vtype: 'numericMask'
            }, {
                fieldLabel: 'Bono %',
                name: 'BonoPct',
                xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true
            }, {
                fieldLabel: 'Bono',
                name: 'BonoImporte',
                xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                enableKeyEvents: true,
                vtype: 'numericMask'
            }, {
                fieldLabel: 'Total Comisiones',
                name: 'TotalCom',
                xtype: 'numberfield',
                listeners: {
                    'keyup': {
                        fn: this.onKeyup2,
                        scope: this
                    }
                },
                readOnly: true,
                vtype: 'numericMask'
            }, {
                fieldLabel: 'Mesa de Control',
                name: 'EstatusMesaDeControl',
                xtype: 'enum.combo',
                enumName: 'Cognitum.Dominio.MesaControl.StatusMesaControl',
                readonly: true,
                disabled: true
            }]
        });
        
        Cognitum.Polizas.General.Componentes.Generales.superclass.initComponent.apply(this, arguments);
    },
    
    onKeyup2: function(field, e){
        this.calculaMonto(field);
    },

    calculaMonto: function(field) {
        if (PLOG.isDebugEnabled()) {
            LOG.debug('[EditorParts.CalculandoMonto] <-');
        }
        var sumatoria = 0;
        var Total = this.getForm().findField('Total');
        var TotalCom = this.getForm().findField('TotalCom');
        var Neto = this.getForm().findField('Neto');
        var ComPorct = this.getForm().findField('ComisionPct');
        var ComImport = this.getForm().findField('ComisionImporte');
        var SobComPorct = this.getForm().findField('SobreComisionPct');
        var SobComImport = this.getForm().findField('SobreComisionImporte');
        var BonoPorct = this.getForm().findField('BonoPct');
        var BonoImport = this.getForm().findField('BonoImporte');
        var RecPorct = this.getForm().findField('RecargosPct');
        var RecImport = this.getForm().findField('RecargosImporte');
        var Impuesto = this.getForm().findField('Impuesto');
        var impuestoEntity = Impuesto.getEntityValue();
        var ImpuestoValue = Ext.isEmpty(impuestoEntity) ? 0 : isNaN(impuestoEntity.Porcentaje) ? 0 : impuestoEntity.Porcentaje;
        var ImpImport = this.getForm().findField('ImpuestoImporte');
        var ImpImportValue = 0;
        var Gastos = this.getForm().findField('Gastos');
        var Prima = this.getForm().findField('Prima');
        var Descuento = this.getForm().findField('Descuento');
        
        if (!Ext.isEmpty(field) && field.getName() == 'ComisionImporte') {
            var valor = (parseFloat(ComImport.getValue()) * 100) / parseFloat(Prima.getValue());
            if (valor == 'NaN') {
                ComPorct.setValue('');
            }
            else {
                ComPorct.setValue(formatAsCurrency(valor));
            }
        }
        else {
            var valor = ((parseFloat(ComPorct.getValue()) / 100) * parseFloat(Prima.getValue()));
            if (valor == 'NaN') {
                ComImport.setValue('');
            }
            else {
                ComImport.setValue(formatAsCurrency(valor));
            }
        }

        if (!Ext.isEmpty(field) && field.getName() == 'SobreComisionImporte') {
            var valor = (parseFloat(SobComImport.getValue()) * 100) / parseFloat(ComImport.getValue());
            if (valor == 'NaN') {
                SobComPorct.setValue('');
            }
            else {
                SobComPorct.setValue(formatAsCurrency(valor));
            }
        }
        else {
            var valor = ((parseFloat(SobComPorct.getValue()) / 100) * parseFloat(ComImport.getValue()));
            if (valor == 'NaN') {
                SobComImport.setValue('');
            }
            else {
                SobComImport.setValue(formatAsCurrency(valor));
            }
        }

        if (!Ext.isEmpty(field) && field.getName() == 'BonoImporte') {
            var valor = (parseFloat(BonoImport.getValue()) * 100) / parseFloat(Prima.getValue());
            if (valor == 'NaN') {
                BonoPorct.setValue('');
            }
            else {
                BonoPorct.setValue(formatAsCurrency(valor));
            }
        }
        else {
            var valor = ((parseFloat(BonoPorct.getValue()) / 100) * parseFloat(Prima.getValue()));
            if (valor == 'NaN') {
                BonoImport.setValue('');
            }
            else {
                BonoImport.setValue(valor);
            }
        }
        
        if (!Ext.isEmpty(field) && field.getName() == 'RecargosImporte') {            
            var valor = (parseFloat(RecImport.getValue()) * 100) / parseFloat(Prima.getValue());
            if (valor == 'NaN') {
                RecPorct.setValue('');
            }
            else {
                RecPorct.setValue(formatAsCurrency(valor));
            }
        }
        else {            
            var valor = (parseFloat(Prima.getValue()) * (parseFloat(RecPorct.getValue()) / 100));
            if (valor == 'NaN') {
                RecImport.setValue('');
            }
            else {
                RecImport.setValue(formatAsCurrency(valor));
            }
        }        
        sumatoria = parseFloat(Gastos.getValue()) + parseFloat(RecImport.getValue());
        Neto.setValue(formatAsCurrency(parseFloat(Prima.getValue()) + sumatoria));
        ImpImport.setValue(formatAsCurrency(parseFloat(Neto.getValue() - parseFloat(Descuento.getValue())) * (parseFloat(ImpuestoValue) / 100)));
        Total.setValue(formatAsCurrency(parseFloat(Neto.getValue()) - parseFloat(Descuento.getValue()) + parseFloat(ImpImport.getValue())));
        TotalCom.setValue(formatAsCurrency(parseFloat(ComImport.getValue()) + parseFloat(SobComImport.getValue()) + parseFloat(BonoImport.getValue())));
        
        if (PLOG.isDebugEnabled()) {
            LOG.debug('[EditorParts.CalculandoMonto] ->');
        }
        
    },
    
    updateControls: function(value){
        if (Ext.isEmpty(value)) {
            return;
        }
        if (value.EstatusPoliza >= 1) {
            this.disable();
        }
        if (!this.isNew) {            
            this.calculaMonto();
        }
    }
    
});

Ext.reg('pol.ctls.gral', Cognitum.Polizas.General.Componentes.Generales);


function formatAsMoney(num) {
    num = num.toString().replace(/$|,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
        num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '' + num + '.' + cents);
}

function formatAsCurrency(num) {
    num = num.toString().replace(/$|,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    /*for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
        num.substring(num.length - (4 * i + 3));*/
    return (((sign) ? '' : '-') + '' + num + '.' + cents);
}


Ext.form.MoneyField = Ext.extend(Ext.form.TextField, {
    fieldClass: "x-form-field x-form-num-field",
    allowDecimals: true,
    decimalSeparator: ".",
    decimalPrecision: 2,
    allowNegative: true,
    minValue: Number.NEGATIVE_INFINITY,
    maxValue: Number.MAX_VALUE,
    minText: "The minimum value for this field is {0}",
    maxText: "The maximum value for this field is {0}",
    nanText: "{0} is not a valid number", baseChars: "0123456789",
    initEvents: function() {
        var allowed = this.baseChars + ''; if (this.allowDecimals) {
            allowed += this.decimalSeparator;
        }
        if (this.allowNegative) { allowed += '-'; }
        this.maskRe = new RegExp('[' + Ext.escapeRe(allowed) + ']'); Ext.form.MoneyField.superclass.initEvents.call(this);
    }, validateValue: function(value) {
        if (!Ext.form.MoneyField.superclass.validateValue.call(this, value)) { return false; }
        if (value.length < 1) { return true; }
        value = String(value).replace(this.decimalSeparator, "."); if (isNaN(value)) { this.markInvalid(String.format(this.nanText, value)); return false; }
        var num = this.parseValue(value); if (num < this.minValue) { this.markInvalid(String.format(this.minText, this.minValue)); return false; }
        if (num > this.maxValue) { this.markInvalid(String.format(this.maxText, this.maxValue)); return false; }
        return true;
        /*var oRegExp = /^\$?[0-9]+(,[0-9]{3})*(\.[0-9]{2})?$/;
        return oRegExp.test();*/
    }, getValue: function() {
        //alert("getValue: " + this.fixPrecision(this.parseValue(Ext.form.MoneyField.superclass.getValue.call(this).replace(",", ""))));        
        return this.fixPrecision(this.parseValue(Ext.form.MoneyField.superclass.getValue.call(this).replace(",", "")));
    }, setValue: function(v) {
        v = typeof v == 'number' ? v : parseFloat(String(v).replace(this.decimalSeparator, ".")); v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator); return Ext.form.MoneyField.superclass.setValue.call(this, v);
    },
    parseValue: function(value) {
        value = parseFloat(String(value).replace(this.decimalSeparator, ".")); return isNaN(value) ? '' : value;
    },
    fixPrecision: function(value) {
        var nan = isNaN(value); if (!this.allowDecimals || this.decimalPrecision == -1 || nan || !value) { return nan ? '' : value; }
        return parseFloat(parseFloat(value).toFixed(this.decimalPrecision));
    },
    beforeBlur: function() {
        var v = this.parseValue(this.getRawValue()); if (!Ext.isEmpty(v)) { this.setValue(this.fixPrecision(v)); }
        Ext.form.MoneyField.superclass.setValue.call(this, formatAsCurrency(Ext.form.MoneyField.superclass.getValue.call(this)));
    },
    afterrender: function(cmp) {
        Ext.form.MoneyField.superclass.setValue.call(this, formatAsCurrency(Ext.form.MoneyField.superclass.getValue.call(this)));
    },
    focus: function(cmp){
        Ext.form.MoneyField.superclass.setValue.call(this, Ext.form.MoneyField.superclass.getValue.call(this).replace(",", ""));
    }
});   Ext.reg('moneyfield', Ext.form.MoneyField);
